package com.yjw.rpc.client;

import com.yjw.rpc.server.RpcRequest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class RpcClientProxy implements InvocationHandler {

    private Class<?> interfaceClass;
    private String host;
    private int port;

    public RpcClientProxy(Class<?> interfaceClass, String host, int port) {
        this.interfaceClass = interfaceClass;
        this.host = host;
        this.port = port;
    }

    public <T> T clientProxy() {
        return (T) Proxy.newProxyInstance(RpcClientProxy.class.getClassLoader(), new Class[]{interfaceClass}, this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 组装请求
        RpcRequest rpcRequest = new RpcRequest();
        rpcRequest.setClassName(method.getDeclaringClass().getName());
        rpcRequest.setMethodName(method.getName());
        rpcRequest.setParameters(args);
        // 通过TCP传输协议传输数据
        TCPTransport tcpTransport = new TCPTransport(host, port);
        return tcpTransport.send(rpcRequest);
    }
}
